import _ from 'lodash';
import * as loginService from '../services/login';
import * as goodsService from '../services/goods';
import * as meyleyService from '../services/meyley';
import { Toast } from 'antd-mobile'
import { Link, browserHistory } from 'dva/router';
import { saveCookie } from '../utils/cookie';

export default {

  namespace: 'meyley',

  state: {
      homeTabType: 'home',
      userInfo: null,
      adList: [],
      category: null,
      shopInfo: null,
      productionDetail: null,
      brandList: null,
      searchProductionInfo: null,
      hotProductions: null
  },

  subscriptions: {
    setup({ dispatch, history }) {  // eslint-disable-line
    },
  },

  effects: {
    *fetch({ payload }, { call, put }) {  // eslint-disable-line
      yield put({ type: 'save' });
    },
    *changeHomeTabType({ payload }, { call, put }) {
      yield put({
        type: 'saveHomeTabType',
        payload: {
          homeTabType: payload
        }
      })
    },
    
    *fetchShopInfo({ payload }, { call, put }) {
      const { data } = yield call(meyleyService.fetchShopInfo, payload)

      yield put({
        type: 'saveShopInfo',
        payload: { 
          shopInfo: data && data.result || []
        }
      })
    },
    *fetchBrandList({ payload }, { call, put }) {
      const { data } = yield call(meyleyService.fetchBrandList)

      yield put({
        type: 'saveBrandList',
        payload: {
          brandList: data && data.result || []
        }
      })
    },
    *fetchCategory({ payload }, { call, put }) {
      const { data } = yield call(meyleyService.fetchCategory)
      yield put({
        type: 'saveCategory',
        payload: {
          category: data && data.result || {}
        }
      })
    },
    *searchProduction({ payload }, { call, put }) {
      const { data } = yield call(goodsService.searchProduction, payload)
      yield put({
        type: 'saveSearchProduction',
        payload: {
          searchProductionInfo: data && data.result || {}
        }
      })
    },
    *fetchProductionDetail({ payload }, { call, put }) {
      const { data } = yield call(goodsService.fetchProductionDetail, payload)
      yield put({
        type: 'saveProductionDetail',
        payload: {
          productionDetail: data && data.result || {}
        }
      })
    },
    *fetchHotProductions({ payload }, { call, put }) {
      const { data } = yield call(goodsService.fetchHots)

      yield put({
        type: 'saveHots',
        payload: {
          hotProductions: data && data.result || {}
        }
      })
    },
    *fetchAds({ payload: values }, { call, put}) {
      const { data } = yield call(goodsService.fetchAds)

      yield put({
        type: 'saveAds',
        payload: {
          ads: data && data.result || {}
        }
      })

    },
    *fetchMembers({ payload }, { call, put}) {
      const { data } = yield call(meyleyService.fetchMembers, payload)

      yield put({
        type: 'saveMembers',
        payload: {
          members: data && data.result || {}
        }
      })

    },
    *login({ payload: values}, { call, put}) {
      const { data } = yield call(loginService.login, values);

      if(data && data.status === 1) {
        // success
        Toast.info(`${data && data.msg}`, 1);
        yield put({
          type: 'saveUserInfo',
          payload: {
            userInfo: {
              ...data.result
            }
          },
        });

        saveCookie('userId', data.result && data.result.userId)
        saveCookie('userName', data.result && data.result.userName)

        // to main page
        window.setTimeout(() => {
          browserHistory.push('/')
        }, 1000)
      } else {
        // error
        Toast.info(`${data && data.msg || '登录失败'}`);
      }
    }
  },

  reducers: {
    saveMembers(state, { payload: { members } }) {
      return { ...state, members }
    },
    saveHomeTabType(state, { payload: { homeTabType } }) {
      return { ...state, homeTabType }
    },
    saveUserInfo(state, { payload: { userInfo } }) {
      return { ...state, userInfo: {...userInfo} }
    },
    saveAds(state, { payload: { ads }}) {
      let { adList, total } = ads

      if(total > 8) {
        adList = adList.splice(0, 7)
      }

      return { ...state, adList }
    },
    saveProductionDetail(state, { payload: { productionDetail }}) {
      return { ...state, productionDetail }
    },
    saveHots(state, { payload: { hotProductions }}) {
        let defaultProduction = {
          goodsThumb: 'default',
          goodsName: 'default',
          shopPrice: 'default',
          isDefault: true
        }
        // process hotProductions to [[{},{},{}], [{},{},{}]]
        if(hotProductions && hotProductions.goodsList) {
          hotProductions.goodsList = _.chunk(hotProductions.goodsList, 3)
          // 如果不足3个，用默认的补齐。
          let lastGoodLine = hotProductions.goodsList[hotProductions.goodsList.length -1]
          if(lastGoodLine && lastGoodLine.length === 1) {
            lastGoodLine.push(defaultProduction)
            lastGoodLine.push(defaultProduction)
          } else if(lastGoodLine && lastGoodLine.length === 2) {
            lastGoodLine.push(defaultProduction)
          }
          return { ...state, hotProductions}
        } else {
          return state
        }
    },
    saveSearchProduction(state, { payload: { searchProductionInfo }}) {
      return { ...state, searchProductionInfo: searchProductionInfo }
    },
    saveCategory(state, { payload: { category }}) {
      return { ...state, category}
    },

    saveBrandList(state, { payload: { brandList }}) {
      return { ...state, brandList }
    },

    saveShopInfo( state, { payload: { shopInfo }}) {
      return { ...state, shopInfo}
    }
  }

};
